<template>
  <div>
<!--  ==================流程定义列表===============  -->
    <a-card v-if="!xmlFrame.open||xmlView">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :md="6" :sm="12">
              <a-form-item label="流程名称">
                <j-input placeholder="请输入名称" v-model="queryParams.name"></j-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="流程分类">
                <a-select v-model="queryParams.categoryId" placeholder="请选择流程分类">
                  <a-select-option value="">请选择</a-select-option>
                  <a-select-option v-for="category in categorys" :key="category.id" :value="category.id">
                    {{category.name}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-col :md="9" :sm="24">
              <a-button type="primary" @click="handleQuery" icon="search" style="margin-left: 21px">查询</a-button>
              <a-button type="primary" @click="resetQuery" icon="reload" style="margin-left: 8px">重置</a-button>
              </a-col>
            </span>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button @click="handleAdd" type="primary" icon="plus">新增流程定义</a-button>
      </div>

      <div>
        <a-table ref="table" size="middle"
          :scroll="{x:true}"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="definitionList"
          :pagination="ipagination"
          :loading="loading"
          class="j-table-force-nowrap"
          @change="handleTableChange">

          <a slot="name" slot-scope="text, record" @click="handleReadImage(record.id)">{{ text }}</a>

          <div slot="useStatus" slot-scope="text,record">
            <a-tag color="blue" v-if="record.useStatus === 0">草稿</a-tag>
            <a-tag color="orange" v-if="record.useStatus === 1">待发布</a-tag>
            <a-tag color="green" v-if="record.useStatus === 2">已发布</a-tag>
            <a-tag color="red" v-if="record.useStatus === -1">禁用</a-tag>
          </div>

          <span slot="action" slot-scope="text, record">
            <a-dropdown>
              <a class="ant-dropdown-link">更多操作 <a-icon type="down" /></a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a @click="handleEdit(record)">
                    <a-icon type="edit" />
                    编辑信息
                  </a>
                </a-menu-item>
                <a-menu-item v-if="record.useStatus === 0">
                  <a @click="handleLoadXml(record)">
                    <a-icon type="edit" />
                    模型设计
                  </a>
                </a-menu-item>
                <a-menu-item v-if="record.useStatus === 0">
                  <a @click="publishModel(record)">
                    <a-icon type="upload" />
                    发布流程
                  </a>
                </a-menu-item>
                <a-menu-item>
                  <a @click="handleUpdateSuspensionState(record, -1)">
                    <a-icon type="play-circle" />
                    禁用
                  </a>
                </a-menu-item>
                <a-menu-item v-if="record.useStatus === 0">
                  <a @click="handleDelete(record)">
                    <a-icon type="delete" />
                    删除
                  </a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </span>
        </a-table>
      </div>
    </a-card>
      <!-- 流程图 -->
    <a-card v-if="xmlFrame.open&&!xmlView" :title="xmlFrame.title">
      <a slot="extra" href="#" @click="()=>{xmlFrame.open=false}">返回</a>
      <bpmn-modeler
        v-if="xmlShow"
        ref="refNode"
        :xml="xmlData"
        :users="users"
        :groups="groups"
        :categorys="categorys"
        :is-view="xmlView"
        @save="save"
      />
    </a-card>

    <!--  弹窗预览  -->
    <a-modal :title="xmlFrame.title" :visible.sync="xmlView && xmlFrame.open" :width="xmlFrame.width"
      :footer="null" closable @cancel="()=>{xmlView=false,xmlFrame.open=false}"
    >
      <bpmn-modeler
        v-if="xmlShow"
        ref="refNode"
        :xml="xmlData"
        :users="users"
        :groups="groups"
        :categorys="categorys"
        :is-view="xmlView"
        @save="save"
      />
    </a-modal>

    <j-modal
      :title="modal.title"
      :width="modal.width"
      :visible="modal.visible"
      switchFullscreen
      @ok="handleOk"
      :okButtonProps="{ class:{'jee-hidden': modal.disableSubmit} }"
      @cancel="handleCancel"
      cancelText="关闭">
      <flow-model-form ref="realForm" @ok="submitCallback" :disabled="modal.disableSubmit"></flow-model-form>
    </j-modal>
  </div>
</template>

<script>
import bpmnModeler from "workflow-bpmn-modeler";
import { deleteAction, getAction, postAction,putAction, downFile,getFileAccessHttpUrl } from '@/api/manage'
import {
  categoryList,
  delDeployment,
  listDefinition,
  readXml,
  roleList,
  saveXml,
  updateState,
  userList
} from "@views/flowable/api/definition";
 import FlowModelForm from './FlowModelForm'

export default {
  components: {
    bpmnModeler,
    FlowModelForm,
  },
  data() {
    return {
      /*===================设计器属性======================*/
      users: [],
      groups: [],
      categorys: [],
      modal:{
        title:'',
        width:896,
        visible: false,
        disableSubmit: false
      },
      /*=================页面属性===================*/
      loading: true,
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      // 总条数
      //total: 0,
      // 流程定义表格数据
      definitionList: [],
      allDefinitionList: [],
      // 查询参数
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        modelName: null,
        categoryId: "",
        categoryName: null,
        useStatus: 1,
        modelKey: null,
        // tenantId: null,
        // deployTime: null,
        // derivedFrom: null,
        // derivedFromRoot: null,
        // parentDeploymentId: null,
        // engineVersion: null
      },
      xmlFrame:{
        width:'70%',
        title:'流程图',
        open: false,
        src: "",
      },
      // xml
      xmlData:"",
      xmlShow: true,
      xmlView: false,
      currentModelData:{},

      columns: [
        {
          title: '#',
          dataIndex: '',
          key:'rowIndex',
          width:60,
          align:"center",
          customRender:function (t,r,index) {
            return parseInt(index)+1;
          }
        },
        {
          title:'流程模型编号',
          align:"center",
          dataIndex: 'id'
        },
        {
          title:'流程标识代号',
          align:"center",
          dataIndex: 'key'
        },
        {
          title:'流程分类',
          align:"center",
          dataIndex: 'categoryName'
        },
        {
          title:'流程名称',
          align:"center",
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' },
        },
        {
          title:'状态',
          align:"center",
          dataIndex: 'useStatus',
          scopedSlots: { customRender: 'useStatus' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          fixed:"right",
          width:147,
          scopedSlots: { customRender: 'action' }
        }
      ],
    };
  },
  created() {
    this.initUserAndRole();
    this.getList();
  },
  methods: {
    /*===============设计器===============*/
    initUserAndRole(){
      userList({}).then(res=>{
        this.users = res.result||[]
        this.users.map(o=>{
          o.id = o.username
          o.name = o.realname
        })
      })
      roleList({}).then(res=>{
        this.groups = res.result||[]
        this.groups.map(o=>{
          o.name = o.roleName
        })
      })
      categoryList({}).then(res=>{
        this.categorys = res.result||[]
      })
    },
    handleAdd () {
        this.modal.visible = true;
        this.modal.title = "新增";
        this.modal.disableSubmit = false;
        this.$nextTick(()=> {
          this.$refs.realForm.add();
        })
    },
    handleEdit (record) {
      this.modal.visible=true;
      this.modal.title = "编辑";
      this.modal.disableSubmit = false;
      this.$nextTick(()=>{

        
        getAction( "/flow/model/"+ record.id).then((res) => {
          if (res.success) {
            this.$refs.realForm.edit(res.result);
          } else {
            that.$message.warning("查询数据失败！"+res.message);
          }
        });

        
      })
    },
    close () {
      this.$emit('close');
      this.modal.visible = false;
    },
    handleOk () {
      this.$refs.realForm.submitForm();
    },
    submitCallback(){
      this.$emit('ok');
      this.modal.visible = false;
      this.getList();
    },
    handleCancel () {
      this.close()
    },


    getModelDetail(id) {
      // 发送请求，获取xml
      readXml(id).then(res =>{
        this.xmlData = res.result.xml;
      })
    },
    getCategoryName(category){
      let find = this.categorys.find(o=>o.id==category);
      if (find){
        return find.name
      }
      return ''
    },
    /*保存流程定义*/
    save(data) {
      console.log(data);  // { process: {...}, xml: '...', svg: '...' }
      console.log(this.currentModelData);  // { process: {...}, xml: '...', svg: '...' }
      
      const params = {
        id: this.currentModelData.id, 
        xml: data.xml
      } 
      saveXml(params).then(res => {
        this.$message.success("保存成功")
        // 关闭当前标签页并返回上个页面
        this.getList()
        this.xmlFrame.open = false
      })
    },
    /*================页面===============*/
    handleQuery() {
      this.queryParams.pageIndex = 1;
      this.queryParams.suspensionState = this.queryParams.useStatus?1:0;
      this.getList();
    },
    handleTableChange(pagination, filters, sorter) {
      this.ipagination = pagination
      this.loadData2()
    },
    /** 查询流程定义列表 */
    getList() {
      this.loading = true;
      // 最新版本
      const param1 = Object.assign({
        isLastVersion:1,
      },this.queryParams)
      listDefinition(param1).then(response => {
        this.definitionList = response.result.records;
        this.ipagination.total = response.result.total;
        this.loading = false;
        for (const definition of this.definitionList) {
          definition.hasChildren = true
        }
      });
      // 所有
      const param2 = Object.assign({
        isLastVersion:0
      },this.queryParams,
      this.ipagination,
      {
        pageSize: 9999,
        pageIndex:1
      })
      listDefinition(param2).then(response => {
        console.log(response)
        this.allDefinitionList = response.result.records;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    /** 打开流程设计弹窗页面 */
    handleLoadXml(row){
      
      if (row&&row.id){
        console.log(row)
        this.currentModelData = row;
        this.handleReadImage(row.id);
        this.xmlView = false
        this.xmlFrame.title = "编辑流程图";
      } else {
        //新增
        this.xmlData = ''
        this.xmlView = false
        this.xmlFrame.open = true
        this.xmlFrame.title = '新增流程'
        this.xmlShow = false
        this.$nextTick(()=>{
          this.xmlShow = true
        })
      }
      this.xmlFrame.width = '90%'
    },
    /** 流程图查看 */
    handleReadImage(id){
      this.xmlFrame.title = "流程图";
      this.xmlFrame.open = true;
      this.xmlFrame.width = '70%';
      // this.xmlFrame.src = process.env.VUE_APP_BASE_API + "/flowable/definition/xmlFrame/" + deploymentId;
      // 发送请求，获取xml
      this.xmlView = true
      readXml(id).then(res =>{
        if (res.success){
           this.xmlShow = true
          this.xmlData = res.result.xml
          /*this.xmlShow = false
          this.$nextTick(()=>{
            this.xmlShow = true
          })*/
        } else {
          this.$message.error("获取流程图失败！")
          
          this.$nextTick(()=>{
             this.xmlShow = false
            this.xmlData = "";
          })

        }
      })
    },
    // 打开业务表单
    handleForm() {
    },
    // 配置业务表单
    handleAddForm(row) {
    },
    /** 挂起/激活流程 */
    handleUpdateSuspensionState(row, status){
       
      const params = {
        id: row.id,
        state: status
      }
      updateState(params).then(res => {
        this.$message.success("更新状态成功");
        this.getList();
      });
    },
    publishModel(row){
       
      const params = {
        modeId: row.id 
      }
      getAction( "/flow/model/publish/"+ row.id, params).then((res) => {
          if (res.success) {
            this.$message.success("发布成功"); 
            this.getList();
          } else {
            this.$message.warning("发布失败！"+res.message);
          }
        });
       
    },

    /** 删除按钮操作 */
    handleDelete(row) { 
      this.$confirm({
        title:"警告",
        content:'是否确认删除流程模型编号为"' + row.id + '"的数据项?',
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        onOk:()=>{
          deleteAction("flow/model/"+ row.id, {id:row.id}).then((res) => {
            this.getList();
            if (res.success){
              this.$message.success('删除成功');
            } else {
              this.$message.success('删除失败');
            }
        });

 
        }
      })
    },
    load(tree, treeNode, resolve) {
      const key = tree.key;
      const childrens = []
      for (const one of this.allDefinitionList) {
        if (one.key==key&&one.id!=tree.id){
          childrens.push(one)
        }
      }
      console.log(tree, treeNode,this.allDefinitionList,childrens)
      resolve(childrens)
    }
  },
  computed: {
    getContainer() {
      return document.querySelector('#app')
    }
  }
};
</script>